package com.atyun;

import com.atyun.gaojin.notify.AlterNotify;
import com.atyun.gaojin.notify.deduplicator.AlterDeduplicator;
import com.atyun.gaojin.notify.deduplicator.impl.RedisAlertDeduplicator;
import com.atyun.rejectPolicy.RejectPolicyProxy;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程池，继承ThreadPoolExecutor
 * @Author: 云水瑶
 * @Date: 2025/4/26
*/
public class DptExecutor extends ThreadPoolExecutor {

    private final AtomicInteger corePoolSize = new AtomicInteger();
    private final AtomicInteger maximumPoolSize = new AtomicInteger();
    private final String poolName;

    public DptExecutor(String poolName, int corePoolSize, int maximumPoolSize, AlterNotify notify, AlterDeduplicator alterDeduplicator) {
        super(corePoolSize,
                maximumPoolSize,
                1, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                new CustomizableThreadFactory(poolName + "-thread-"),
                RejectPolicyProxy.createProxy(
                        new ThreadPoolExecutor.AbortPolicy(),
                        poolName,
                        notify,
                        alterDeduplicator
                ));
        this.corePoolSize.set(corePoolSize);
        this.maximumPoolSize.set(maximumPoolSize);
        this.poolName = poolName;
    }

    public static class ExecutorContext {

    }

    public boolean casUpdateCorePoolSize(int expect, int update) {
        return corePoolSize.compareAndSet(expect, update);
    }

    public boolean casUpdateMaximumPoolSize(int expect, int update) {
        return maximumPoolSize.compareAndSet(expect, update);
    }

    /**
     * 线程池执行任务核心入口
     * 在此处会动态设置核心线程与最大线程参数
     * 通过自定义逻辑，延迟参数的动态更新
     * @Author: 云水瑶
     * @Date: 2025/4/26
    */
    @Override
    public void execute(Runnable command) {
        BlockingQueue<Runnable> queue = getQueue(); //获取任务队列
        RejectedExecutionHandler rejectHandler = getRejectedExecutionHandler();//获取执行拒绝策略的handler

//        super.execute(command);
        int corePool = corePoolSize.get();
        int maxPool = maximumPoolSize.get();

        if(NacosListener.flag) {
            System.out.println("延迟p1线程池动态参数修改：核心线程：" + corePool + " 最大线程: " + maxPool);
            if(corePool != getCorePoolSize()) super.setCorePoolSize(corePool);
            if(maxPool != getMaximumPoolSize()) super.setMaximumPoolSize(maxPool);
        }
        //获取当前正在执行任务的线程数量
        int activeCount = getActiveCount();
        //获取任务队列的任务数量
        int queueSize = queue.size();
        //获取所有线程数量，包括执行任务的和未执行任务的
        int poolSize = getPoolSize();
        //获取任务队列剩余容量
        int remaining = queue.remainingCapacity();
        //查看当前execute是否已关闭
        boolean shutdown = isShutdown();
        System.out.println("当前执行任务的线程数量：" + activeCount + "\n 当前任务队列容量: " + queueSize + "\n当前任务队列剩余容量: " + remaining + "\n\n");

        if(shutdown) {
            //执行器已关闭，需要指向拒绝策略
            rejectHandler.rejectedExecution(command, this);
            return;
        }
        super.execute(command);

//        //策略：只有在真正需要创建线程时才应用新参数
//        if(getPoolSize() < corePool) {
//            super.setCorePoolSize(corePool);
//            super.setMaximumPoolSize(maxPool);
//            super.execute(command);
//        } else if(getMaximumPoolSize() < maxPool) {
//            super.setCorePoolSize(corePool);
//            super.setMaximumPoolSize(maxPool);
//            super.execute(command);
//        } else {
//            //执行拒绝策略
//            super.getRejectedExecutionHandler().rejectedExecution(command, this);
//        }
    }
}
